# coding=utf-8

import importlib, sys
import csv
import re

importlib.reload(sys)

from pymongo import MongoClient


class MonGo():
    def __init__(self):
        pass

    def monogodb_txt(self, url, ps):
        myclient = MongoClient(url)

        mydb = myclient.zufang

        collection = mydb.zufang
        rows = []
        items = collection.find({}, {"rental": 1, "size": 1, "name": 1, "_id": 0, "area": 1, "house_type": 1, "mode": 1})
        headers = ['size', 'rental']
        with open('myhouse.csv', 'a+', newline='') as f:
            for item in items:
                rows.append({"size": re.findall(r"\d+", item["size"])[0], "rental": item["rental"]})
            f_csv = csv.DictWriter(f, headers)
            if ps is True:
                f_csv.writeheader()
            f_csv.writerows(rows)


if __name__ == "__main__":
    mongo = MonGo()
    mongo.monogodb_txt("mongodb://localhost:27017/", ps=True)
    mongo.monogodb_txt("mongodb://129.28.33.83:27017/", ps=False)
